package com.szbmyoubao.app.ui.main.home

import com.szbmyoubao.app.http.DebugService
import com.szbmyoubao.app.http.RetrofitClient
import com.szbmyoubao.app.http.ServerConfig
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.http.launchFlow

/**
 * @author ellecity06
 * @time 2024/10/22 14:49
 * @des
 */
class HomeViewModel : BaseMviViewModel<HomeState, HomeIntent>() {

    override suspend fun collectIntent(it: HomeIntent) {
        when (it) {
            is HomeIntent.FetchDebugAppInfo -> fetchDebugAppInfo(it.code)
        }
    }

    private fun fetchDebugAppInfo(code: String) {
        if (code.length > 8) {
            // 不是短链
            val debugService = RetrofitClient.getService(DebugService::class.java, ServerConfig.Companion.pgyerHost)
            launchFlow({
                debugService.getByAppKey(
                    apiKey = ServerConfig.Companion.pgyerApiKey,
                    appKey = ServerConfig.Companion.pgyerAppKey,
                    buildKey = code
                )
            }, success = {
                if (it != null) {
                    postState(HomeState.AppInfoSuccessFul(it))
                }
            })
        } else {
            val debugService = RetrofitClient.getService(DebugService::class.java, ServerConfig.Companion.pgyerHost)
            launchFlow({ debugService.getByShortcut(apiKey = ServerConfig.Companion.pgyerApiKey, buildShortcutUrl = code) }, success = {
                if (it != null) {
                    postState(HomeState.AppInfoSuccessFul(it))
                }
            })
        }

    }
}